﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using DeepEarth.Core.Utilities;
using DeepEarth.Map.Core;
using DeepEarth.Toolkit.Common;
using System.Linq;
using DeepEarth.Map.Core.Tiling;

namespace DeepEarth.Toolkit.Controls
{
	[TemplatePart(Name = PART_overlayModesSelector, Type = typeof(ItemsControl))]
	public class OverlayModesSelector : MapInteractionControl
	{
		private const string PART_overlayModesSelector = "PART_overlayModesSelector";
		private ItemsControl _modeSelector;


		public static readonly DependencyProperty OrientationProperty =
			DependencyProperty.Register("Orientation",
			                            typeof (Orientation),
			                            typeof (OverlayModesSelector),
			                            new PropertyMetadata(Orientation.Horizontal));

		public Orientation Orientation
		{
			get { return (Orientation)GetValue(OrientationProperty); }
			set { SetValue(OrientationProperty, value); }
		}

		public OverlayModesSelector()
		{
			DefaultStyleKey = typeof(OverlayModesSelector);
		}

		public override void OnApplyTemplate()
		{
			base.OnApplyTemplate();
			_modeSelector = (ItemsControl)GetTemplateChild(PART_overlayModesSelector);
		}

		protected override void ViewChanged(MapView newView, MapView oldView)
		{
			if (_modeSelector == null) return;
			if (oldView != null)
				oldView.PropertyChanged -= MapViewPropertyChanged;
			
			if (newView == null) return;
			newView.PropertyChanged += MapViewPropertyChanged;
			OnMapViewModeChanged(newView.TileSourceProvider);
		}

		void MapViewPropertyChanged(object sender, PropertyChangedEventArgs e)
		{
			if (_modeSelector == null) return;

			//refresh controls only if the "Mode" property is changed;
			if (e.PropertyName != BindingUtilities.PropertyName(() => View.TileSourceProvider)) return;

			var mode = View.TileSourceProvider;
			
			OnMapViewModeChanged(mode);
		}

		private void OnMapViewModeChanged(BaseTileSourceProvider mode)
		{
			_modeSelector.ClearValue(ItemsControl.ItemsSourceProperty);

			IList<MapMode> overlayModes;
			if (mode == null || (overlayModes = mode.AvailableOverlayModes.ToList()).Count == 0)
			{
				IsVisible = false;
				return;
			}

			IsVisible = true;

			var models = overlayModes.Select(x => new OverlayModeViewModel(x, mode));
			_modeSelector.ItemsSource = models;	
		}
	}
}
